package com.bootx.service.impl;

import com.bootx.common.CommonAttributes;
import com.bootx.pojo.RedPackageInfo;
import com.bootx.service.AiService;
import jakarta.annotation.Resource;
import org.apache.commons.io.FileUtils;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.content.Media;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Service;
import org.springframework.util.MimeTypeUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author black
 */
@Service
public class AiServiceImpl implements AiService {

    @Resource
    private ChatClient chatClient;

    @Override
    public Map<Integer, List<RedPackageInfo.RedPackageItem>> process(File[] children) {
        Map<Integer, List<RedPackageInfo.RedPackageItem>> data = new ConcurrentHashMap<>();
        int totalTasks = children.length;
        int maxConcurrency = 5;
        ExecutorService executor = Executors.newFixedThreadPool(maxConcurrency);
        List<Callable<List<RedPackageInfo.RedPackageItem>>> taskList = new ArrayList<>();
        // 红包个数
        AtomicReference<Integer> count = new AtomicReference<>(0);

        // 构造任务，确保顺序
        for (int i = 0; i < totalTasks; i++) {
            final int taskId = i;
            taskList.add(() -> {
                FileSystemResource resource = new FileSystemResource(children[taskId]);
                UserMessage userMessage = UserMessage.builder()
                        .text(CommonAttributes.PROMPT)
                        .media(new Media(MimeTypeUtils.IMAGE_PNG, resource)).build();
                try {
                    RedPackageInfo entity = chatClient.prompt().messages(userMessage).call().entity(new ParameterizedTypeReference<RedPackageInfo>() {
                    });
                    if(entity!=null){
                        if(entity.getCount()!=null && entity.getCount()>0){
                            count.set(entity.getCount());
                        }
                        return entity.getRedPackageItemList();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            });
        }

        List<Future<List<RedPackageInfo.RedPackageItem>>> futures = null;
        try {
            futures = executor.invokeAll(taskList);
        } catch (InterruptedException ignored) {
        }finally {
            for (File child : children) {
                try {
                    FileUtils.delete(child);
                }catch (Exception ignored){
                }
            }
        }
        List<RedPackageInfo.RedPackageItem> list = new ArrayList<>();
        // 获取并输出结果（保持顺序）
        for (Future<List<RedPackageInfo.RedPackageItem>> future : futures) {
            try {
                list.addAll(future.get());
            } catch (ExecutionException | InterruptedException e) {
                System.out.println("任务失败: " + e.getMessage());
            }
        }
        executor.shutdown();
        data.put(count.get(), list);
        return data;
    }
}
